package com.car.loan.common.utils;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;


/**
 * @author huangding
 * @description
 * @date 2019/3/20 14:57
 */
public class ObjectStruct {

    private Object object = null;
    private Map<String, Method> getMethods = null;
    private Map<String, Method> setMethods = null;
    private Set<String> fieldNames = null;

    public ObjectStruct(Object object) {
        this.object = object;
    }

    private void structMethods() {
        Method[] methods = this.object.getClass().getMethods();
        this.getMethods = new HashMap();
        this.setMethods = new HashMap();

        for (int i = 0; methods != null && i < methods.length; ++i) {
            String methodName = methods[i].getName();
            if (methodName.length() >= 4) {
                String field = methodName.substring(3, 4).toLowerCase();
                if (methodName.length() > 4) {
                    field = field + methodName.substring(4);
                }

                if (methodName.startsWith("get") && methodName.length() > 3) {
                    this.getMethods.put(field, methods[i]);
                } else if (methodName.startsWith("set") && methodName.length() > 3) {
                    this.setMethods.put(field, methods[i]);
                }
            }
        }

    }

    public Object getMethod(String methodName, Object[] args) {
        Class c[] = null;
        if (args != null) {
            int len = args.length;
            c = new Class[len];
            for (int i = 0; i < len; ++i) {
                c[i] = args[i].getClass();
            }
        }
        try {
            Method method = this.object.getClass().getMethod(methodName, c);
            return method.invoke(object, args);
        } catch (Exception e) {
            e.printStackTrace();
            throw new NullPointerException("获取方法出现异常，请查询原因");
        }
    }


    public Map<String, Method> getSetMethods() {
        if (this.setMethods == null) {
            this.structMethods();
        }

        return this.setMethods;
    }

    public Set<String> getFieldNames() {
        return this.fieldNames;
    }

    public Map<String, Method> getGetMethods() {
        if (this.getMethods == null) {
            this.structMethods();
        }

        return this.getMethods;
    }
}
